﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ExChange.Model;
using System.Text;
using System.IO;
using System.Net;
using System.Transactions;

namespace ExChange.Web.Controllers
{
    public class WeChatController : Controller
    {
        public JFDHEntities entity = new JFDHEntities();

        public Model.Member LoginMember
        {
            get
            {
                if (Session["SessionLoginMember"] == null)
                {
                    return null;
                }
                else
                {
                    return (Model.Member)Session["SessionLoginMember"];
                }
            }
            set
            {
                Session["SessionLoginMember"] = value;
            }
        }

        public int WareID
        {
            get
            {
                if (Session["SessionWareID"] == null)
                {
                    return 0;
                }
                else
                {
                    return Int32.Parse(Session["SessionWareID"].ToString());
                }
            }
            set
            {
                Session["SessionWareID"] = value;
            }
        }

        public string LoginSmsCode
        {
            get
            {
                if (Session["SessionLoginSmsCode"] == null)
                {
                    return "";
                }
                else
                {
                    return Session["SessionLoginSmsCode"].ToString();
                }
            }
            set
            {
                Session["SessionLoginSmsCode"] = value;
                Session.Timeout = 20;
            }
        }

        public string LoginPhone
        {
            get
            {
                if (Session["SessionLoginPhone"] == null)
                {
                    return "";
                }
                else
                {
                    return Session["SessionLoginPhone"].ToString();
                }
            }
            set
            {
                Session["SessionLoginPhone"] = value;
                Session.Timeout = 2;
            }
        }

        public ActionResult Index()
        {
            bool isIos = false;
            String[] iOS = new String[] { "iphone", "ios", "ipad" };
            String wx = "micromessenger";
            String agent = Request.UserAgent.ToLower();
            //FileCache.Set("agent", agent);
            //if (agent.IndexOf(wx) < 0)
            //{
            for (int i = 0, j = iOS.Length; i < j; i++)
            {
                if (agent.IndexOf(iOS[i]) >= 0)
                {
                    isIos = true;
                }
            }
            //}
            ViewBag.IsIos = isIos;

            ViewBag.SettingList = entity.Setting.ToList();
            return View();
        }

        public JsonResult SendCodeAjax()
        {
            string phone = Request["phone"];
            bool isOk = false;
            long number = 0;
            isOk = long.TryParse(phone, out number);
            JsonData json = new JsonData();
            if (isOk)
            {
                if (LoginSmsCode.IsNullOrWhiteSpace())
                {
                    var member = entity.Member.FirstOrDefault(x => x.Phone == phone && x.IsActive == false);
                    if (member != null)
                    {
                        var order = entity.Order.FirstOrDefault(x => x.UserID == member.ID);
                        if (order == null)
                        {
                            Random ran = new Random();
                            int code = ran.Next(1000, 9999);
                            LoginPhone = phone;
                            LoginSmsCode = code.ToString();
                            SendSmsCode(phone, LoginSmsCode);
                            json.Success("验证码已发送");
                        }
                        else
                        {
                            json.message = "此账户已兑换";
                        }
                    }
                    else
                    {
                        json.message = "无此会员信息";
                    }
                }
                else
                {
                    json.message = "发送验证码过快，请稍后重新尝试";
                }
            }
            else
            {
                json.message = "手机号码错误";
            }

            return Json(json, JsonRequestBehavior.AllowGet);
        }

        public JsonResult LoginAjax()
        {
            string phone = Request["phone"];
            string code = Request["code"];
            string loginname = Request["loginname"];
            string password = Request["password"];
            JsonData json = new JsonData();
            if (!string.IsNullOrEmpty(code))
            {

                if (LoginPhone == phone)
                {
                    if (LoginSmsCode == code)
                    {
                        var member = entity.Member.FirstOrDefault(x => x.Phone == phone);
                        if (member == null)
                        {
                            json.message = "此手机号码无兑换礼品";
                        }
                        if (member != null && member.IsActive.HasValue && member.IsActive.Value)
                        {
                            json.message = "此手机号码已兑换礼品";
                        }
                        LoginMember = member;
                        json.Success();
                        json.data = "/WeChat/Ware?levels="+ member.Member_Ware.ID;
                    }
                    else
                    {
                        json.message = "验证码错误";
                    }
                }
                else
                {
                    json.message = "与发送短信的手机号码不一致";
                }
            }
            else
            {
                var member = entity.Member.FirstOrDefault(x => x.loginname == loginname && x.password == password);
                if (member == null)
                {
                    var order = entity.Order.FirstOrDefault(x => x.UserID == member.ID);
                    if (order != null)
                    {
                        json.message = "此账户已兑换";
                        return Json(json, JsonRequestBehavior.AllowGet);
                    }
                    json.message = "此手机号码无兑换礼品";
                }
                if (member != null && member.IsActive.HasValue && member.IsActive.Value)
                {
                    json.message = "此手机号码已兑换礼品";
                    return Json(json, JsonRequestBehavior.AllowGet);
                }
                LoginMember = member;
                json.Success();
                json.data = "/WeChat/Ware?levels=" + member.Member_Ware.ID;
            }
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Order()
        {
            int id = Int32.Parse(Request["id"]);
            int levels = Int32.Parse(Request["levels"]);
            var mw = entity.Member_Ware.Include("Member").FirstOrDefault(x => x.ID == levels);
            var ids = mw.WareIds.Split(',').Where(f => !string.IsNullOrEmpty(f)).Select(p => Convert.ToInt32(p)).ToList();
            //var warelist = entity.Ware.Where(f => ids.Contains(f.ID)).ToList();
            var warelist = from o in entity.Ware where ids.Contains(o.ID) select o;
            var ware = warelist.FirstOrDefault(x => x.ID == id);
            if (ware == null)
            {
                return Content("商品错误，没有兑换权限！");
            }
            WareID = ware.ID;
            ViewBag.Wear = ware;
            ViewBag.levels = levels;
            return View();
        }

        public JsonResult OrderAjax()
        {
            string username = Request["username"];
            string phone = Request["phone"];
            string address = Request["address"];
            string zipcode = Request["zipcode"];
            string levels = Request["levels"];
            JsonData json = new JsonData();
            var dingdan = entity.Order.FirstOrDefault(f => f.Phone == phone);
            if (dingdan != null)
            {
                json.message = "该手机号已兑换！";
                return Json(json, JsonRequestBehavior.AllowGet);
            }
            var ware = entity.Ware.FirstOrDefault(x => x.ID == WareID);

            var order = new Model.Order()
            {
                Address = address,
                CreateTime = DateTime.Now,
                Phone = phone,
                State = (int)EnumHelper.OrderState.未发货,
                UserName = username,
                WareName = ware.Name,
                WarePrice = ware.Pirce,
                ZipCode = zipcode,
            };
            int mwareid = -1;
            if (int.TryParse(levels, out mwareid))
            {
                order.MWareID = mwareid;
                order.MWareName = entity.Member_Ware.FirstOrDefault(f => f.ID == mwareid) == null ? "" : entity.Member_Ware.FirstOrDefault(f => f.ID == mwareid).Memberlevel;
            }
            //添加订单
            if (LoginMember != null)
            {
                order.UserID = LoginMember.ID;
                //修改会员
                var member = entity.Member.FirstOrDefault(f => f.ID == LoginMember.ID&&f.IsValid.Value==true);
                if (member.IsActive.HasValue && member.IsActive.Value)
                {
                    json.message = "只能兑换一次！";
                    return Json(json, JsonRequestBehavior.AllowGet);
                }
                member.IsActive = true;
                order.MWareID = member.Member_Ware == null ? -1 : member.Member_Ware.ID;
                order.MWareName = member.Member_Ware == null ? "" : member.Member_Ware.Memberlevel;
                entity.Entry<Model.Member>(member).State = EntityState.Modified;
            }
            entity.Order.Add(order);
            //修改商品数量
            ware.Count = ware.Count - 1;
            ware.ConvertedQuantity = ware.ConvertedQuantity + 1;
            entity.Entry<Model.Ware>(ware).State = EntityState.Modified;
            try
            {
                entity.SaveChanges();
                json.Success();
            }
            catch (Exception)
            {
                json.message = "下单失败";
            }
            //if (row> 0)
            //{
            //    json.Success();
            //    ////var entity2 = new JFDHEntities();
            //    //var member = entity.Member.FirstOrDefault(f => f.ID == LoginMember.ID);
            //    //member.IsActive = true;
            //    //entity.Entry<Model.Member>(member).State = EntityState.Modified;

            //    //if (entity.SaveChanges() > 0)
            //    //{
            //    //    json.Success();
            //    //}
            //    //else
            //    //{
            //    //    json.message = "修改状态失败";
            //    //}
            //}
            //else
            //{
            //    json.message = "下单失败";
            //}
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Ware()
        {
            ViewBag.LoginMember = LoginMember;
            ViewBag.levels = LoginMember == null ? Request["levels"] : LoginMember.Levels.ToString();
            return View();
        }
        /// <summary>
        /// 二维码扫描页面
        /// </summary>
        /// <returns></returns>
        public ActionResult djindex(int djid)
        {
            if (entity.Member_Ware.FirstOrDefault(f => f.ID == djid) == null)
            {
                return Content("会员等级无效");
            }
            ViewBag.djid = djid;
            return View();
        }

        public JsonResult WareList()
        {
            string index = Request["index"];
            int Levels = int.Parse(Request["levels"]);
            int size = 4;
            var mw = entity.Member_Ware.Include("Member").FirstOrDefault(x => x.ID == Levels);
            var ids = mw.WareIds.Split(',').Where(f => !string.IsNullOrEmpty(f)).Select(p => Convert.ToInt32(p)).ToList();
            //var warelist = entity.Ware.Where(f => ids.Contains(f.ID)).ToList();
            var warelist = from o in entity.Ware where ids.Contains(o.ID) where o.Count > 0 select o;
            int have = warelist.Count() > (Int32.Parse(index) * size) ? 1 : 0;
            warelist = warelist.OrderByDescending(f => f.ID).Skip((Int32.Parse(index) - 1) * size).Take(size);
            return Json(new { have = have, list = warelist.ToList() }, JsonRequestBehavior.AllowGet);
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string url = filterContext.RequestContext.HttpContext.Request.Url.AbsolutePath;
            string request = Request["request"];
            if (request != "1")
            {
                if (!Request.UserAgent.ToLower().Contains("micromessenger"))
                {
                    Response.Write("<span style='font-size:24px;'>请用微信打开</span>");
                    Response.End();
                }
                //else
                //{
                //if (url.IndexOf("Login") < 0 && url.IndexOf("Index") < 0 && url.IndexOf("Ajax") < 0)
                //{
                //    filterContext.HttpContext.Response.Clear();
                //    filterContext.HttpContext.Response.Write("<script>window.parent.parent.parent.location='/WeChat/Index';</script>");
                //    filterContext.HttpContext.Response.End();
                //}
                //}
            }
            ViewBag.request = request;
            ViewBag.Title = "礼多娇兑礼网";
        }

        //private void SendSmsCode(string phone, string code)
        //{
        //    string api = "http://sms.tintcloud.com/?mobile={0}&code={1}";
        //    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(api, phone, code));
        //    request.Method = "GET";
        //    request.ContentType = "application/x-www-form-urlencoded";
        //    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //    Stream myResponseStream = response.GetResponseStream();
        //    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
        //    string retString = myStreamReader.ReadToEnd();
        //    myStreamReader.Close();
        //    myResponseStream.Close();

        //}

        string PostUrl = "http://sms.253.com/msg/send";
        public void SendSmsCode(string phone, string code)
        {
            string un = System.Configuration.ConfigurationManager.AppSettings["SMSUN"].ToString();
            string pw = System.Configuration.ConfigurationManager.AppSettings["SMSPWD"].ToString();
            string content = "【礼多娇兑礼网】您好！验证码是：" + code + "，短信有效时间为2分钟。";
            string postStrTpl = "un={0}&pw={1}&phone={2}&msg={3}&rd=1";
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] postData = encoding.GetBytes(string.Format(postStrTpl, un, pw, phone, content));
            System.GC.Collect();
            HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(PostUrl);
            myRequest.KeepAlive = false;
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = postData.Length;
            myRequest.Timeout = 5000;
            Stream newStream = myRequest.GetRequestStream();
            // Send the data.
            newStream.Write(postData, 0, postData.Length);
            newStream.Flush();
            newStream.Close();
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            if (myResponse.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                myResponse.Close();
                myRequest.Abort();
            }
            else
            {
                myRequest.Abort();
                myResponse.Close();
            }
        }
    }
}
